package io.mvvm.ws.handler;

import com.alibaba.fastjson.JSON;
import io.mvvm.ws.entity.RequestInfo;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @program: Netty
 * @description: 消息解码器
 * @author: 潘
 * @create: 2021-04-28 22:17
 **/
@Component
@ChannelHandler.Sharable
public class WebSocketDeCoderHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public static final String HANDLER_NAME = "WebSocketDeCoderHandler";

    private static Logger logger = LoggerFactory.getLogger(WebSocketDeCoderHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String text = msg.text();
        // 验证是否为json，如果不是，则关闭通道
        if (!hasJson(text)) {
            logger.warn("非法数据格式 : {}", text);
            ctx.channel().close();
            return;
        }

        RequestInfo requestInfo = JSON.parseObject(text, RequestInfo.class);
        super.channelRead(ctx, requestInfo);
    }
    /**
     * 验证是否为JSON格式
     *
     * @param text
     * @return
     */
    private boolean hasJson(String text) {
        try {
            JSON.parseObject(text);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
